<?php
namespace app\common\only;

/*
 *  让获取数据只执行一次，主要作用用来避免反复查询
 */
class Base {
	protected $prefix = '';
	protected static $mount = []; //挂载数据，方便各种方法把返回值挂载到这里

	//获取值
	public function get($name, $fun = null, $argments = []) {
		$key = $this->get_key($name);
		return $this->getNoPrefix($key, $fun, $argments);
	}

	//强制更新
	public function update($name, $fun = null, $argments = []) {
		$key = $this->get_key($name);
		return $this->updateNoPrefix($key, $fun, $argments);
	}

	//给key添加前缀，区别不同的类
	public function get_key($key) {
		if($this->prefix) {
			$key = $this->prefix . '__' . $key;
		}
		return $key;
	}

	//获取值
	public function getNoPrefix($key, $fun = null, $argments = []) {
		$mount = &static::$mount; //指向应用，方便修改挂载值
		if(!isset($mount[$key])) { //如果没有挂载就更新数据
			return $this->updateNoPrefix($key, $fun, $argments);
		}
		return $mount[$key];
	}

	//强制更新
	public function updateNoPrefix($key, $fun = null, $argments = []) {
		if(!$fun) { //如果方法参数为空，就找同名方法
			$fun = $key;
		}

		if(is_string($fun)) { //如果是字符串就调用类本身的同名方法
			$mount[$key] = $this->$fun(...$argments);
			return $mount[$key];
		} else {
			$mount[$key] = $fun(...$argments);
			return $mount[$key];
		}
		return $this;
	}
}